package com.huazheng.miaosha.web.controller;

import com.google.common.util.concurrent.RateLimiter;
import com.huazheng.miaosha.web.constant.ErrorEnum;
import com.huazheng.miaosha.web.entity.StockOrderEntity;
import com.huazheng.miaosha.web.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author: zhanghzi
 * @Email: zhanghzi@dcits.com
 * @Date: 2021/1/23 19:57
 * Description: TODO
 */
@RestController
@RequestMapping("/order")

public class OrderController {
    private static final Logger LOGGER = LoggerFactory.getLogger(OrderController.class);

    @Resource
    private OrderService orderService;

    //初始化令牌，每秒放行10个请求
    RateLimiter rateLimiter = RateLimiter.create(100);

    @RequestMapping("/create/{sid}")
    public String createOrder(@PathVariable int sid) {
        LOGGER .info("购买物品编号sid=[{}]", sid);
        StockOrderEntity order=null;
        int id=0;
        try {
            id = orderService.createOrder(sid);
            LOGGER.info("创建订单id: [{}]", id);
        } catch (Exception e) {
            LOGGER.error("Exception", e);
        }
        return String.valueOf(id);
    }

    @RequestMapping("/hello")
    public String hello(){
        return "hell world";
    }

    /*/**
      * @Description 添加乐观锁防止超卖
      * @author  zhanghuazheng
      * @Date    2021/1/24 13:42
      * @param   [sid]
      * @return  java.lang.String
      **/
    @RequestMapping("/create/lock/{sid}")
    public String createOrderByOptisLock(@PathVariable int sid) {
        LOGGER .info("购买物品编号sid=[{}]", sid);
        int id=0;
        try {
            id = orderService.createOrderWithOptisLock(sid);
            LOGGER.info("创建订单id: [{}]", id);
        } catch (Exception e) {
            LOGGER.error("Exception", e);
        }
        return String.valueOf(id);
    }

    /*/**
      * @Description 通过令牌桶限流
      * @author  zhanghuazheng
      * @Date    2021/1/24 13:43
      * @param   [sid]
      * @return  java.lang.String
      **/
    @RequestMapping("/create/limit/{sid}")
    public String createOrderByOptisLockWithlp(@PathVariable int sid) {
        LOGGER .info("购买物品编号sid=[{}]", sid);

        //阻塞式
        boolean acquire = rateLimiter.tryAcquire(1000, TimeUnit.MILLISECONDS);
        //非阻塞
//        boolean acquire = rateLimiter.tryAcquire();
        if(!acquire){
            LOGGER.error("请求太多，已超过设置的阈值");
            return ErrorEnum.REQUEST_OVER.toString();
        }
        int id=0;
        try {
            id = orderService.createOrderWithOptisLock(sid);
            LOGGER.info("创建订单id: [{}]", id);
        } catch (Exception e) {
            LOGGER.error("Exception", e);
        }
        return String.valueOf(id);
    }


}
